/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 Université Joseph Fourier
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */
package org.osami.gateway.mediator.jms.sender;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Map;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import org.osgi.service.log.LogService;

import fr.liglab.adele.cilia.Data;
import fr.liglab.adele.cilia.framework.ISender;

/**
 * This mediator send all the data it receives on a JMS Queue.
 * 
 * @author bourretp
 */
public class JmsQueueProducerSender implements ISender {

    private String m_instanceName;

    // The JNDI names of the JMS resources needed by this mediator
    
    private String m_queueConnectionFactoryName;

    private String m_queueName;

    // The needed resources retrieved via JNDI
    private volatile QueueConnectionFactory m_queueConnectionFactory;
    private volatile Queue m_queue;

    // Logger
    private LogService m_logger;

    // Retrieve the JMS QueueSession via JNDI
    public synchronized void start() {
        // Need to switch TCCL for JNDI lookup
        ClassLoader old = Thread.currentThread().getContextClassLoader();
        try {
            // Replace the TCCL with this bundle class loader (dynamic imports
            // must be enabled)
            Thread.currentThread().setContextClassLoader(
                    JmsQueueProducerSender.class.getClassLoader());
            // Get JNDI initial context
            InitialContext context;
            try {
                context = new InitialContext();
            } catch (Exception e) {
                log(LogService.LOG_ERROR, "Cannot get JNDI initial context", e);
                throw new RuntimeException(e);
            }
            // Get JMS QueueConnectionFactory
            try {
                m_queueConnectionFactory = (QueueConnectionFactory) context
                        .lookup(m_queueConnectionFactoryName);
            } catch (Exception e) {
                log(LogService.LOG_ERROR,
                        "Cannot get JMS QueueConnectionFactory", e);
                throw new RuntimeException(e);
            }
            // Get JMS Queue
            try {
                m_queue = (Queue) context.lookup(m_queueName);
            } catch (Exception e) {
                log(LogService.LOG_ERROR, "Cannot get JMS Queue", e);
                throw new RuntimeException(e);
            }
            // Log success
            log(LogService.LOG_INFO, "Started");
            log(LogService.LOG_DEBUG, "queueConnectionFactory.name = "
                    + m_queueConnectionFactoryName);
            log(LogService.LOG_DEBUG, "queue.name = " + m_queueName);
        } finally {
            // Restore TCCL
            Thread.currentThread().setContextClassLoader(old);
        }
    }

    // Release references
    public synchronized void stop() {
        m_queueConnectionFactory = null;
        m_queue = null;
        // Log success
        log(LogService.LOG_INFO, "Stopped");
    }

    // Send Method
    public boolean send(Data data) {
        
        // Send it via JMS
        try {
        	// Get the content of the data
        	Object content = data.getContent();
            if (content instanceof byte[]) {
                // Byte array
                byte[] array = (byte[]) data.getContent();
                sendByteArrayMessage(array);
            } else if (content instanceof Serializable) {
                // Sens MapMessage
                sendSerializableObjectMessage((Serializable) content);
            } else if (content instanceof Map) {
                // Sens MapMessage
                Map<String, Serializable> map = (Map<String, Serializable>) data.getContent();
                sendMapMessage(map);
            } else if (content instanceof String) {
                // TextMessage
                String message = data.getContent().toString();
                sendTextMessage(message);
            } else {
            	// Create a map with the properties of the map
            	sendSerializableObjectMessage((Hashtable) data.getAllData());
            }
            log(LogService.LOG_DEBUG, "Message sent via JMS : " + data.toString());
        } catch (JMSException e) {
            // Log
            log(LogService.LOG_ERROR, "Cannot send message", e);
			return false;
        }/* catch (IOException e) {
        	log(LogService.LOG_ERROR, "Cannot send message", e);
			return false;
		}*/
        return true;
    }

    // Send the specified data via JMS
    private void sendByteArrayMessage(byte[] bytes) throws JMSException {
        QueueConnection connection = m_queueConnectionFactory
                .createQueueConnection();
        // TODO make this a little more configurable...
        QueueSession session = connection.createQueueSession(false,
                Session.AUTO_ACKNOWLEDGE);
        MessageProducer messageProducer = session.createProducer(m_queue);
        // Create the JMS bytes message.
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(bytes);
        // Send the message using the producer.
        messageProducer.send(message);
        //close connection & session
        session.close();
        connection.close();
    }

    // Send the specified data via JMS
    private void sendMapMessage(Map<String, Serializable> map) throws JMSException {
        QueueConnection connection = m_queueConnectionFactory
                .createQueueConnection();
        // TODO make this a little more configurable...
        QueueSession session = connection.createQueueSession(false,
                Session.AUTO_ACKNOWLEDGE);
        MessageProducer messageProducer = session.createProducer(m_queue);
        // Create the JMS bytes message.
        MapMessage message = session.createMapMessage();

        // Directly inject the Map content in the message
        message.setObject("content", map);
        // Send the message using the producer.
        messageProducer.send(message);
        //close connection & session
        session.close();
        connection.close();
    }

    private void sendTextMessage(String msg) throws JMSException {
    	QueueConnection connection = m_queueConnectionFactory
    	.createQueueConnection();
    	// TODO make this a little more configurable...
    	QueueSession session = connection.createQueueSession(false,
    			Session.AUTO_ACKNOWLEDGE);
    	MessageProducer messageProducer = session.createProducer(m_queue);
    	// Create the JMS bytes message.
    	TextMessage message = session.createTextMessage();
    	message.setText(msg);
    	// Send the message using the producer.
    	messageProducer.send(message);
    	//close connection & session
    	session.close();
    	connection.close();
    }
    
    private void sendSerializableObjectMessage(Serializable msg) throws JMSException {
    	QueueConnection connection = m_queueConnectionFactory
    	.createQueueConnection();
    	// TODO make this a little more configurable...
    	QueueSession session = connection.createQueueSession(false,
    			Session.AUTO_ACKNOWLEDGE);
    	MessageProducer messageProducer = session.createProducer(m_queue);
    	// Create the JMS bytes message.
    	ObjectMessage message = session.createObjectMessage(msg);
    	// Send the message using the producer.
    	messageProducer.send(message);
    	//close connection & session
    	session.close();
    	connection.close();
    }

    // Utility methods

    private void log(int level, String message, Throwable throwable) {
        m_logger.log(level, m_instanceName + " - " + message, throwable);
    }

    private void log(int level, String message) {
        log(level, message, null);
    }
    
    public byte[] convert(Object obj) throws IOException {
    	ObjectOutputStream os = null;
    	ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000);
    	os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
    	os.flush();
    	os.writeObject(obj);
    	os.flush();
    	byte[] sendBuf = byteStream.toByteArray();
    	os.close();
    	
    	return sendBuf;
    	}

}
